const { TimeRange } = require('../../util')
Parse.Cloud.beforeSave('RcOrder', async (req, res) => {
  try {
    const order = req.object
    if (order.id) return
    const buyerCashRecord = new Parse.Object('RcCashRecord')
    const sellerCashRecord = new Parse.Object('RcCashRecord')

    const price = order.get('price')
    const orderName = order.get('orderName')
    const payWay = order.get('payWay')
    const seller = order.get('seller')
    const buyer = order.get('buyer')
    const orderNo = order.get('orderNo')
    const resource = order.get('resource')
    const vip = order.get('vip')
    if (vip) {
      const current = await new Parse.Query('RcVip').equalTo('objectId', vip.id).first()
      const months = current.get('months')
      let memberVip = await new Parse.Query('RcMemberVip').equalTo('circle', current.get('circle')).equalTo('member', buyer).first() || new Parse.Object('RcMemberVip', {'circle': current.get('circle'), member: buyer})
      let endDate = memberVip.get('endDate')
      if (endDate && endDate.getTime() > Date.now()) {
        endDate.setMonth(endDate.getMonth() + months)
        memberVip.set('endDate', endDate)
        memberVip.set('startDate', new Date())
      } else {
        endDate = new Date()
        endDate.setMonth(endDate.getMonth() + months)
        memberVip.set('endDate', endDate)
        memberVip.set('startDate', new Date())
      }
      memberVip = await memberVip.save()
      order.set('memberVip', memberVip)
      res.success()
    } else {
      res.success()
      // 资源买出数
      order.get('resource').increment('buyTotal', 1).save()
    }
    const isNew = !await new Parse.Query('RcCashRecord').equalTo('type', 'sell').equalTo('member', seller).count()

    // 买入记录
    buyerCashRecord.save({
      type: 'buy',
      orderName: `买入${orderName}`,
      payWay,
      seller,
      buyer,
      orderNo,
      member: buyer,
      price,
      resource,
      vip
    })

    // 买出记录
    sellerCashRecord.save({
      type: 'sell',
      orderName: `卖出${orderName}`,
      payWay,
      seller,
      buyer,
      orderNo,
      member: seller,
      price,
      resource,
      vip
    })

    // 更新收入
    const Wallet = await new Parse.Query('RcWallet').equalTo('member', seller).first() || new Parse.Object('RcWallet', {
      member: seller
    })
    Wallet.increment('total', +price).save()

    // 新订单数
    seller.increment('newOrderTotal', 1).set('wallet', Wallet).save()

    const timeRange = new TimeRange()
    const thisDay = timeRange.thisDay()
    const orderCount = await new Parse.Query('RcOrderCount').equalTo('type', 1).greaterThan('createdAt', thisDay[0]).lessThanOrEqualTo('createdAt', thisDay[1]).first() || new Parse.Object('RcOrderCount', {type: 1})
    const totalCount = await new Parse.Query('RcOrderCount').equalTo('type', 0).first() || new Parse.Object('RcOrderCount', {type: 0})
    const config = await Parse.Config.get()
    const shareRate = config.get('RcShareRate')

    const shareMoney = parseFloat((price * shareRate / 100).toFixed(2))
    await orderCount.increment('price', order.get('price')).increment('number', 1).increment('shareMoney', shareMoney).save()
    await totalCount.increment('price', order.get('price')).increment('number', 1).increment('shareMoney', shareMoney).save()

    const cashCount = await new Parse.Query('RcCashCount').first() || new Parse.Object('RcCashCount')
    cashCount.increment('remaining', price).increment('total', price)

    if (isNew) {
      cashCount.increment('memberCount', 1)
    }
    await cashCount.save()
  } catch (err) {
    console.log(err)
  }
})


const test = async () => {
  await new Parse.Object('RcOrder', {
    buyer: new Parse.Object('RcMember', {id: 'rr3pRzfA7C'}),
    seller: new Parse.Object('RcMember', {id: 'kTnOiY6pWH'}),
    resource: new Parse.Object('RcResource', {id: '9m0SadmvxH'}),
    orderNo: `${new Date().getTime()}${parseInt(Math.random() * 100, 10)}`,
    orderName: '该好好。',
    price: 100,
    payTime: new Date(),
    status: 1,
    payWay: 'weixin'
  }).save()
}

const apply = async () => {
  await new Parse.Object('RcCashRecord', {
    type: 'withdraw',
    money: 100,
    member: new Parse.Object('RcMember', {id: 'kTnOiY6pWH'}),
    status: 0,
    payWay: 'weixin',
    memberName: 'test',
    orderNo: `${Date.now()}${parseInt(Math.random() * 100)}`
  }).save()
}

// test()

// apply()

